import { OpenAPI } from '@/client/core/OpenAPI';
import { useEffect, useState } from 'react';

// 自定义钩子函数来管理WebSocket连接
function useWebSocket(deviceId: number, maxMessages: number = 100) {
  const [messages, setMessages] = useState<string[]>([]);

  useEffect(() => {
    const url = OpenAPI.BASE + '/api/v1/web/ws'
    console.log(url)
    const ws = new WebSocket(url);

    ws.onopen = () => {
      console.log('WebSocket connection established');
    };

    ws.onmessage = (event) => {
      const message = JSON.parse(event.data);
      if (message.device_id !== deviceId) {return}
      
      setMessages(prevMessages => {
        const newMessages = [...prevMessages, message.log];
        // 如果消息数量超过最大限制，保留最新的消息
        if (newMessages.length > maxMessages) {
          return newMessages.slice(-maxMessages);
        }
        return newMessages;
      });
    };

    ws.onclose = () => {
      console.log('WebSocket connection closed');
    };

    return () => {
      ws.close();
    };
  }, [deviceId, maxMessages]);

  return messages;
}

export default useWebSocket

